package com.campus.controller;

import com.campus.common.JWTUtil;
import com.campus.common.core.Result;
import com.campus.common.core.TableData;
import com.campus.model.TSysUser;

import com.campus.model.dto.TSysUserCreateDto;
import com.campus.model.dto.UserSelectCondition;
import com.campus.service.ISysUserService;
import com.campus.service.IUserRoleService;
import com.campus.web.vo.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sysUser")
@Api(tags = "用户管理")
public class SysUserController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IUserRoleService roleService;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<String> login(@RequestParam String loginName, @RequestParam String password) {
        // 使用Mybatis-Plus查询用户
        TSysUser loginUser = userService.selectUser(loginName, password);
        // 只有登录成功才需要jwt
        if (loginUser == null) {
            return Result.error("登录失败,用户名或密码错误");
        }
       // 生成token
        String token = JWTUtil.createToken(loginUser);
        // 登录成功后把token返回给前端
        return Result.success(token, "登录成功");

    }

    @PostMapping("/create")
    @ApiOperation("创建用户")
    public Result<Integer> create(@RequestBody TSysUserCreateDto userCreateDto) {
        return Result.to(userService.insertUser(userCreateDto));
    }

    @GetMapping("/select")
    @ApiOperation("查询用户")
    public TableData<TSysUser> select(UserSelectCondition userSelectCondition) {
        List<TSysUser> tSysUsers = userService.selectUserByCondition(userSelectCondition);
        return TableData.success(tSysUsers,Long.valueOf(tSysUsers.size()));
    }

}